﻿using YourLastOptionsDialog.Controls;

namespace YourLastOptionsDialog.ViewModels.Options
{
    /// <summary>
    /// A validator for string values.
    /// </summary>
    public class StringValidator : RegularExpressionValidator
    {
        private int _maxLength = int.MaxValue;

        /// <summary>
        /// Gets or sets the minimum allowed length of the string.
        /// </summary>
        public int MinLength
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the maximum allowed length of the string.
        /// </summary>
        public int MaxLength
        {
            get
            {
                return _maxLength;
            }

            set
            {
                _maxLength = value;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="StringValidator"/> class.
        /// </summary>
        /// <param name="regularExpression">The regular expression to use for validation.</param>
        /// <param name="validationErrorMessage">The validation error message.</param>
        public StringValidator(string regularExpression, string validationErrorMessage)
            : base(regularExpression, validationErrorMessage)
        {
        }

        /// <summary>
        /// Validates the specified input and returns a <see cref="ValidationResult"/> with the outcome of the validation.
        /// </summary>
        /// <param name="input">The input value to validate.</param>
        /// <returns>
        /// The result of the validation.
        /// </returns>
        public override ValidationResult Validate(string input)
        {
            // check min/max
            if (input == null)
            {
                if (MinLength > 0)
                {
                    return new ValidationResult(false, ValidationErrorMessage);
                }
                else
                {
                    return ValidationResult.Success;
                }
            }

            if (input.Length < MinLength || input.Length > MaxLength)
            {
                return new ValidationResult(false, ValidationErrorMessage);
            }

            // use the base regex to validate
            return base.Validate(input);
        }
    }
}